package com.benyanyi.picker;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.benyanyi.picker.base.BaseDialogRecyclerAdapter;
import com.benyanyi.picker.bean.PickerBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YanYi
 * @date 2020/6/22 11:42
 * @email ben@yanyi.red
 * @overview
 */
class PickerDialog extends Dialog {

    private boolean isCache;

    private RecyclerView titleRecycler;
    //    private View titleView;
    private RecyclerView msgRecycler;

    private TextView titleTv;

    private String title = "";

    /**
     * 数据源
     */
    private Map<String, List<PickerBean<?>>> oMap = new HashMap<>();

    /**
     * 标题数据
     */
    private Map<String, List<String>> titleMap = new HashMap<>();

    /**
     * 每次选择位于数据源对应的下标
     */
    private Map<String, List<Integer>> indexMap = new HashMap<>();
    /**
     * 内容数据
     */
    private Map<String, List<PickerBean<?>>> msgMap = new HashMap<>();
    /**
     * map对应的key
     */
    private String key;

    private PickerTitleAdapter titleAdapter;
    private PickerMsgAdapter msgAdapter;

    private PickerHelper.PickerCallback pickerCallback;

    private int index = -1;

    public PickerDialog(@NonNull Context context, boolean isCache) {
        super(context);
        this.isCache = isCache;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weight_picker_view);
        this.titleRecycler = findViewById(R.id.picker_title_recycler);
//        titleView = findViewById(R.id.picker_title_view);
        this.msgRecycler = findViewById(R.id.picker_msg_recycler);
        this.titleTv = findViewById(R.id.picker_title);
        this.titleTv.setText(this.title);
        findViewById(R.id.picker_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        initTitle();
        initMsg();
        setViewLocation();
        setCanceledOnTouchOutside(false);//外部点击取消
        setCancelable(false);
    }

    private void initTitle() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        this.titleRecycler.setLayoutManager(layoutManager);
        this.titleAdapter = new PickerTitleAdapter(getContext(), this.titleMap.get(this.title));
        this.titleRecycler.setAdapter(this.titleAdapter);
        this.titleAdapter.setOnItemListener(new BaseDialogRecyclerAdapter.OnItemListener() {
            @Override
            public void onItemListener(int position) {//标题栏点击事件
                PickerDialog.this.index = position;
                if (DataUtil.isListNotEmpty(PickerDialog.this.oMap.get(PickerDialog.this.title))) {
                    List<String> list = new ArrayList<>(PickerDialog.this.titleMap.get(PickerDialog.this.title));
                    List<Integer> iList = new ArrayList<>(PickerDialog.this.indexMap.get(PickerDialog.this.title));
                    if (DataUtil.isListNotEmpty(list) && position < list.size() - 1) {
                        PickerDialog.this.titleMap.get(PickerDialog.this.title).clear();
                        PickerDialog.this.indexMap.get(PickerDialog.this.title).clear();
                        PickerDialog.this.msgMap.get(PickerDialog.this.title).clear();
                        for (int i = 0; i <= PickerDialog.this.index; i++) {
                            PickerDialog.this.titleMap.get(PickerDialog.this.title).add(list.get(i));
                            PickerDialog.this.indexMap.get(PickerDialog.this.title).add(iList.get(i));
                        }
                        if (DataUtil.isListNotEmpty(PickerDialog.this.indexMap.get(PickerDialog.this.title))) {
                            PickerDialog.this.msgAdapter.setSelectPosition(PickerDialog.this.indexMap.get(PickerDialog.this.title).get(PickerDialog.this.index));
                        } else {
                            PickerDialog.this.titleMap.get(PickerDialog.this.title).add("请选择");
                            PickerDialog.this.msgAdapter.setSelectPosition(-1);
                        }
                        if (position == 0) {
                            PickerDialog.this.msgMap.get(PickerDialog.this.title).addAll(PickerDialog.this.oMap.get(PickerDialog.this.title));
                        } else {
                            PickerBean pickerBean = PickerDialog.this.oMap.get(PickerDialog.this.title).get(PickerDialog.this.indexMap.get(PickerDialog.this.title).get(PickerDialog.this.indexMap.get(PickerDialog.this.title).size() - 1));
                            PickerDialog.this.msgMap.get(PickerDialog.this.title).addAll(pickerBean.getList());
                        }
                        PickerDialog.this.titleAdapter.notifyDataSetChanged(PickerDialog.this.titleMap.get(PickerDialog.this.title));
//                    tabSelectedIndicatorAnimation(titleAdapter.getTextView()).start();
                        PickerDialog.this.msgAdapter.notifyDataSetChanged(PickerDialog.this.msgMap.get(PickerDialog.this.title));
                        PickerDialog.this.titleRecycler.scrollToPosition(PickerDialog.this.titleMap.get(PickerDialog.this.title).size() - 1);
                        PickerDialog.this.msgRecycler.scrollToPosition(PickerDialog.this.indexMap.get(PickerDialog.this.title).get(PickerDialog.this.index));
                    }
                }
            }
        });
    }

    private void initMsg() {
        PickerDialog.this.msgRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        PickerDialog.this.msgAdapter = new PickerMsgAdapter(getContext(), PickerDialog.this.msgMap.get(PickerDialog.this.title));
        PickerDialog.this.msgRecycler.setAdapter(PickerDialog.this.msgAdapter);
        PickerDialog.this.msgAdapter.setOnItemListener(new BaseDialogRecyclerAdapter.OnItemListener() {
            @Override
            public void onItemListener(int position) {
                if (PickerDialog.this.msgMap.get(PickerDialog.this.title).size() > 0) {
                    PickerBean bean = PickerDialog.this.msgMap.get(PickerDialog.this.title).get(position);
                    if (PickerDialog.this.index > -1) {
                        PickerDialog.this.indexMap.get(PickerDialog.this.title).set(PickerDialog.this.indexMap.get(PickerDialog.this.title).size() - 1, position);
                        PickerDialog.this.index = -1;
                    } else {
                        PickerDialog.this.indexMap.get(PickerDialog.this.title).add(position);
                    }

                    PickerDialog.this.titleMap.get(PickerDialog.this.title).set(PickerDialog.this.titleMap.get(PickerDialog.this.title).size() - 1, bean.getName());
                    PickerDialog.this.titleAdapter.notifyDataSetChanged(PickerDialog.this.titleMap.get(PickerDialog.this.title));
                    PickerDialog.this.msgAdapter.setSelectPosition(position);
                    PickerDialog.this.msgAdapter.notifyItemChanged(position);
                    if (DataUtil.isListNotEmpty(bean.getList())) {
                        PickerDialog.this.titleMap.get(PickerDialog.this.title).add("请选择");
                        PickerDialog.this.msgMap.get(PickerDialog.this.title).clear();
                        PickerDialog.this.msgMap.get(PickerDialog.this.title).addAll(bean.getList());
                        PickerDialog.this.msgAdapter.setSelectPosition(-1);
                        PickerDialog.this.msgAdapter.notifyDataSetChanged(PickerDialog.this.msgMap.get(PickerDialog.this.title));
                        PickerDialog.this.msgRecycler.scrollToPosition(0);
//                tabSelectedIndicatorAnimation(titleAdapter.getTextView()).start();
                    } else {
                        dismiss();
                        if (PickerDialog.this.pickerCallback != null) {
                            PickerDialog.this.pickerCallback.callback(PickerDialog.this.titleMap.get(PickerDialog.this.title), PickerDialog.this.indexMap.get(PickerDialog.this.title));
                        }
                    }
                } else {
                    dismiss();
                    if (PickerDialog.this.pickerCallback != null) {
                        PickerDialog.this.pickerCallback.callback(new ArrayList<String>(), new ArrayList<Integer>());
                    }
                }
            }
        });
    }

    /**
     * 设置dialog位于屏幕底部
     */
    private void setViewLocation() {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int height = dm.heightPixels;
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.x = 0;
        lp.y = height;
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = DimensUtils.dip2px(getContext(), 400);
        // 设置显示位置
        onWindowAttributesChanged(lp);
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }

    public void setPickerCallback(PickerHelper.PickerCallback pickerCallback) {
        this.pickerCallback = pickerCallback;
    }

    public <T extends PickerBean<?>> void show(String title, List<T> list) {
        super.show();
        this.key = title;
        List<T> l = list;
        if (!isNotEmpty(this.key)) {
            this.key = "dialog";
        }
        if (list.isEmpty()) {
            l = new ArrayList<>();
        }
        if (isCache && !this.key.equals("dialog") && !this.oMap.isEmpty() && DataUtil.isListNotEmpty(oMap.get(this.key))) {
            if (DataUtil.isListEmpty(indexMap.get(this.key))) {
                this.titleMap.put(this.key, new ArrayList<String>());
                this.indexMap.put(this.key, new ArrayList<Integer>());
                this.msgMap.put(this.key, new ArrayList<PickerBean<?>>());
                this.index = -1;
                this.titleMap.get(this.key).add("请选择");
                this.msgMap.get(this.key).addAll(oMap.get(this.key));
            } else {
                index = indexMap.get(this.key).get(indexMap.get(this.key).size() - 1);
            }
            this.title = this.key;
        } else {
            this.oMap.put(this.key, (List<PickerBean<?>>) l);
            this.titleMap.put(this.key, new ArrayList<String>());
            this.indexMap.put(this.key, new ArrayList<Integer>());
            this.msgMap.put(this.key, new ArrayList<PickerBean<?>>());
            this.index = -1;
            this.titleMap.get(this.key).add("请选择");
            this.msgMap.get(this.key).addAll(oMap.get(this.key));
            if (this.key.equals("dialog")) {
                this.title = "";
            } else {
                this.title = this.key;
            }

        }
        if (this.titleTv != null) {
            if (TextUtils.isEmpty(this.title)) {
                this.titleTv.setText("");
            } else {
                this.titleTv.setText(this.title);
            }
        }
        this.msgAdapter.setSelectPosition(this.index);
        this.titleAdapter.notifyDataSetChanged(this.titleMap.get(this.title));
        this.msgAdapter.notifyDataSetChanged(this.msgMap.get(this.title));
        if (DataUtil.isListNotEmpty(this.titleMap.get(this.title))) {
            this.titleRecycler.scrollToPosition(this.titleMap.get(this.title).size() - 1);
        } else {
            this.titleRecycler.scrollToPosition(0);
        }
        if (DataUtil.isListNotEmpty(this.indexMap.get(this.title))) {
            this.msgRecycler.scrollToPosition(this.index);
        } else {
            this.msgRecycler.scrollToPosition(0);
        }
    }

    private boolean isNotEmpty(String str) {
        return str != null && !TextUtils.isEmpty(str) && !"null".equals(str) && !str.trim().isEmpty();
    }

//    /**
//     * tab 选中的红色下划线动画
//     */
//    private AnimatorSet tabSelectedIndicatorAnimation(View tab) {
//        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(titleView, "X", titleView.getX(), tab.getX());
//
//        final ViewGroup.LayoutParams params = titleView.getLayoutParams();
//        ValueAnimator widthAnimator = ValueAnimator.ofInt(params.width, tab.getMeasuredWidth());
//        widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                params.width = (int) animation.getAnimatedValue();
//                titleView.setLayoutParams(params);
//            }
//        });
//
//        AnimatorSet set = new AnimatorSet();
//        set.setInterpolator(new FastOutSlowInInterpolator());
//        set.playTogether(xAnimator, widthAnimator);
//
//        return set;
//    }

}
